<?php
require_once 'asido/class.asido.php';

class Gallery_Backend_Photos_Edit extends Kernel_Action_Form_Simple 
{
    
    /**
     * Path to the file template.
     *
     * @var string
     */
    protected $_template = 'gallery/backend/photos/form.tpl';
    
    /**
     * Основная таблица, в которой хранится редактируемый элемент.
     *
     * @var string
     */
    protected $_table = 'photos';
    
    /**
     * Элементы основной таблицы, которые нужно исключить из формы.
     *
     * @var array
     */
    protected $_exclude = array('added_at');
    
    /**
     * Initialize form elements. 
     *
     */
    protected function _initElements() 
    {
        parent::_initElements();
        
        $this->_setElementParam('category_id', array(
            'type' => 'list', 
            'values' => Gallery_Backend_Utils::convertToList(
                Kernel_Util_Tree::convert(
                    Gallery_Backend_Utils::getCategories())), 
            'value' => Gallery_Backend_Utils::activeFilter(), 
            ));
        $this->_setElementParam('file', array(
            'type' => 'file', 
            'save' => array($this, 'file'), 
            'validators' => array(
                array('image', array(
                    'types' => Kernel_Config::get('gallery', 'photo_types'), 
                    'message_unsupported_type' => 'PHOTO_UNSUPPORTED_TYPE',
                ))
            )));
        
        if ($file_name = Gallery_Utils::getFileName($this->id)) {
            $this->_setElementParam('file', array(
                'value' => new Kernel_Form_Value_File_Existing('file', 
                Gallery_Utils::photoSorage() . $file_name), 
                ));
            Application::getResponse()->assign('file_storage', 
                Kernel_Config::get('gallery', 'photo_sorage'));
        }
        
        $this->_setAsRequired('file');

		$user_tags = Gallery_Model_UserTags::getInstance()->getTags($this->id);
		$this->_addElement('tags', 'string', array(
			'value' => implode(', ', array_values($user_tags)),
		));
		$this->_setElementPosition('tags', 3);
    }

	/**
     * Реализация обработки пользовательского запроса.
     *
     */
    protected function _process()
    {
		parent::_process();

		// tags suggestion 
		Application::getResponse()->assign('tags_suggestion',
			json_encode(array_values(Gallery_Model_Tags::getInstance()->getTags())));
	}
    
    /**
     * Update current record.
     *
     */
    protected function _update() 
    {
        // before update new photo unlink the old one
        if (Gallery_Utils::getFileName($this->id) != $this->_getValue('file')->__toString()) {
            Gallery_Utils::unlinkFile(Gallery_Utils::getFileName($this->id));
        }
        
        parent::_update();
    }

	/**
     * @desc Save form data.
     *
     * @throws  Kernel_Form_Exception_Save
     */
    protected function _save()
    {
		parent::_save();

		// store tags
		Gallery_Model_UserTags::getInstance()
			->setTags($this->id, $this->_getValue('tags'));
	}
    
    /**
    * Resize uploaded preview image
    * 
    * @param Kernel_Form_Value_File $file
    */
    public function file(Kernel_Form_Value_File $file) 
    {
        Asido::driver('gd');
        $tmp_path = $file->getPath();
        $image_name = generate_file_name($file->getExtension());
        list($org_width, $org_height, , ) = getimagesize($tmp_path);
        
        
        // create thumb
        $thumb = Asido::image($tmp_path, Gallery_Utils::photoThumbSorage() . $image_name);
        Asido::width($thumb, Kernel_Config::get('gallery', 'photo_thumb_width'));
        $thumb->save(ASIDO_OVERWRITE_ENABLED);
        
        
        // create full image
        $image = Asido::image($tmp_path, Gallery_Utils::photoSorage() . $image_name);
        
        if ($org_width > $org_height) {
            $needed_width = Kernel_Config::get('gallery', 'photo_max_width');
            if ($org_width > $needed_width) {
                Asido::width($image, $needed_width);
                $image->save(ASIDO_OVERWRITE_ENABLED);
            } else {
                $file->move(Gallery_Utils::photoSorage() . $image_name);
            }
        } else {
            $needed_height = Kernel_Config::get('gallery', 'photo_max_height');
            if ($org_height > $needed_height) {
                Asido::height($image, $needed_height);
                $image->save(ASIDO_OVERWRITE_ENABLED);
            } else {
                $file->move(Gallery_Utils::photoSorage() . $image_name);
            }
        } 
        
        $file->assign(Gallery_Utils::photoSorage() . $image_name);
    }
    
    protected function _done() 
    {
        $this->redirect_url .= '&' . Gallery_Backend_Utils::FILTER . '=' . $this->_getValue('category_id');
        parent::_done();
    }
    
}